package com.hxd.mall.module.account.verifycode

import android.view.MotionEvent
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.hxd.mall.R
import com.hxd.mall.base.BaseInjectActivity
import com.hxd.mall.constant.HxdConstants
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.login_or_register_phone_num
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.login_or_register_type
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.register_invite_code
import com.hxd.mall.constant.HxdConstants.TB_auther_isgo
import com.hxd.mall.constant.HxdConstants.from_login_to_verifyCode
import com.hxd.mall.constant.HxdConstants.from_register_to_verifyCode
import com.hxd.mall.constant.HxdConstantsAccount
import com.hxd.mall.constant.HxdConstantsAccount.isLogin
import com.hxd.mall.constant.HxdConstantsAccount.mobile_register
import com.hxd.mall.constant.HxdConstantsRouterPath.PathAccount.path_bind_phone
import com.hxd.mall.constant.HxdConstantsRouterPath.PathAccount.path_verify_code
import com.hxd.mall.module.account.bean.LoginBean
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.saveStringData
import com.hxd.mall.utils.local.NavigationUtil.routerNavigation
import com.hxd.mall.utils.local.StackManageUtil
import com.hxd.mall.utils.local.get_code_box_clivck
import com.hxd.mall.utils.local.sendPoint
import com.hxd.mall.utils.open.CountDownTimerUtil.startTimer
import com.hxd.mall.utils.open.ToastUtil
import com.hxd.mall.widget.verifycode.VerifyCodeView
import com.hxd.threelibrary.baichuan.ShoppingUtils
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_verify_code_layout.*
import org.jetbrains.anko.editText

/**
 * @author zhaoyong
 * @description: 验证码页面
 * @date :2019-10-15 15:26
 */
@Route(path = path_verify_code)
class VerifyCodeActivity : BaseInjectActivity<IVerifyCodePresenter>(), IVerifyCodeView {

    private lateinit var phoneNum: String
    /**
     * 0登录
     * 1注册
     */
    private var form: Int = from_login_to_verifyCode
    /**
     * 邀请码
     */
    private lateinit var inviteCode: String
    private var countDownTimer: Disposable? = null
    private val WX_PackageName = "com.tencent.mm"
    private var mCurrentType = 1

    override fun attachLayoutRes(): Int = R.layout.activity_verify_code_layout

    override fun initViews() {
        setTitleCommon()
        setPhoneNum()
        registerClick()
        //调用在setPhoneNum之后
        sendVerifyCode()

        //设置埋点
        sendPoint(get_code_box_clivck)
    }

    override fun showSendVerifyCodeStatus(success: Boolean, tip: String?) {
        if (success) {
            ToastUtil.showToast(getString(R.string.verifycode_send_succes))
            verifyCodeSend.visibility = View.VISIBLE
        } else {
            ToastUtil.showToast(tip ?: getString(R.string.verifycode_send_fail))
        }
    }

    override fun loginStatus(t: LoginBean) {
        val token = t?.data?.accessToken
        if (token != null) {
            if (token.isNotEmpty()) {
                isLogin = true
                HxdConstantsAccount.token = token
                saveStringData("token", token)
                if (!t.data.isBindWx && ShoppingUtils.checkPackage(this, WX_PackageName) && mCurrentType == mobile_register) {
                    //如果微信没有授权 并且微信已经安装
                    routerNavigation(path_bind_phone)
                } else {
                    ToastUtil.showToast("登录成功")
                    StackManageUtil.loginOut(this)
                }
            }
        }
    }

    override fun registerStatus(success: Boolean, t: LoginBean) {
        if (success) {
            isLogin = true
            TB_auther_isgo = true
            HxdConstantsAccount.token = t?.data?.accessToken
            saveStringData("token", t?.data?.accessToken ?: "")
            if (t.data?.isBindWx == false && ShoppingUtils.checkPackage(this, WX_PackageName) && mCurrentType == mobile_register) {
                //如果微信没有授权 并且微信已经安装
                routerNavigation(path_bind_phone)
            } else {
                ToastUtil.showToast("登录成功")
                StackManageUtil.loginOut(this)
            }
        }
    }

    private fun sendVerifyCode() {
        startCountDownTimer()
        mCurrentType = intent.getIntExtra(HxdConstants.IntentParamsKeyDefine.login_bind_view, 1)
        mPresenter?.getVerifyCode(phoneNum)
    }

    private fun registerClick() {
        sendCode.setOnClickListener {
            sendVerifyCode()
        }
        verifyCode.setInputCompleteListener(object : VerifyCodeView.InputCompleteListener {
            override fun inputComplete() {
                when (form) {
                    from_login_to_verifyCode -> {
                        mPresenter?.login(
                            phoneNum, verifyCode.editContent, if (mCurrentType == mobile_register) {
                                mCurrentType
                            } else {
                                3
                            }
                        )
                    }
                    from_register_to_verifyCode -> {
                        mPresenter?.register(
                            phoneNum,
                            verifyCode.editContent,
                            inviteCode,
                            if (mCurrentType == mobile_register) {
                                mCurrentType
                            } else {
                                2
                            }
                        )
                    }
                }
            }

            override fun invalidContent() {
            }

        })
    }

    private fun startCountDownTimer() {
        if (countDownTimer != null && countDownTimer?.isDisposed == true)
            countDownTimer?.dispose()
        countDownTimer = startTimer(60, {
            changeSendCodeStatus(false)
        }, {
            changeSendCodeStatus(true, it)
        })
    }

    private fun changeSendCodeStatus(counting: Boolean, time: Long = 0) {
        sendCode.run {
            if (counting) {
                isClickable = false
                text = getString(R.string.login_input_phone_verify_code_send, time)
                setTextColor(resources.getColor(R.color.color_999999))
                setBackgroundResource(0)
            } else {
                isClickable = true
                text = getString(R.string.login_send_verify_code_desc_again)
                setTextColor(resources.getColor(R.color.color_E24840))
                setBackgroundResource(R.drawable.shape_btn_orange_ring_bg)
            }
        }
    }

    private fun setPhoneNum() {
        phoneNum = intent.getStringExtra(login_or_register_phone_num) ?: ""
        form = intent.getIntExtra(login_or_register_type, from_login_to_verifyCode)
        inviteCode = intent.getStringExtra(register_invite_code) ?: "parent"
        verifyCodeSend.text = getString(R.string.login_input_phone_verify_code_tip_desc, phoneNum)
    }

    override fun initData() {

    }

    override fun onDestroy() {
        super.onDestroy()
        countDownTimer?.dispose()
    }
}